<template>
  <div class="wrape-content">
    <div class="top">
      <img src="../assets/user-image/location.png" alt="位置" />
      <span>您当前所在的位置：通知公告管理</span>
    </div>
    <div class="content">
      <div class="form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="80px"
          class="ruleForm"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入通知公告标题"></el-input>
          </el-form-item>
          <el-form-item label="发布日期" prop="send_time">
            <el-date-picker
              v-model="ruleForm.send_time"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择发布日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="发布人" prop="send_peopel">
            <el-input v-model="ruleForm.send_peopel" placeholder="请输入发布人姓名"></el-input>
          </el-form-item>

          <el-form-item>
            <section class="oprtionbtn">
              <el-button type="primary" class="feicuilu" size="small" @click="getNoticData">查询</el-button>
              <el-button size="small" @click="resetForm('ruleForm')">重置</el-button>
            </section>
          </el-form-item>
        </el-form>
      </div>
      <section class="opreation">
        <el-button type="primary" class="feicuilu addbtn" @click="addNotci">
          <img src="../assets/add.png" />新增
        </el-button>
      </section>
      <div class="Table">
        <el-table
          :height="height"
          :data="Noticdata"
          style="width:97%; margin:0 auto"
          border
          background="rgb(235,245,255)"
        >
          >
          <el-table-column
            v-for="(item,index) in tableHeaderData"
            :key="index"
            :show-overflow-tooltip="true"
            :width="item.width"
            :prop="item.prop"
            :label="item.label"
            align="center"
          ></el-table-column>
          <el-table-column label="文件下载" align="center">
            <template slot-scope="scope">
              <div>
                <span
                  @click="dowloadfile(scope.row.dowloadfile)"
                  style="color:#24b3b3;cursor:pointer;"
                >{{scope.row.dowloadfile?'查看':'无'}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130">
            <template slot-scope="scope">
              <div class="actionbtn" style=" background:#000000">
                <img @click="detail(scope.row)" src="../assets/details.png" title="详细信息" />
              </div>
              <div class="actionbtn" style="background:#24B3B3">
                <img @click="upDataNotic(scope.row)" src="../assets/edit.png" title="修改" />
              </div>
              <div class="actionbtn" style="background:#03a9f4" title="置顶">
                <img
                  style="width:12px;height:14px"
                  @click="topNotic(scope.row)"
                  src="../assets/zhiding.png"
                  title="置顶"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current_page"
        :page-sizes="[15, 50, 100]"
        :page-size="sizepage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog :title="Notictitle" width="60%" center :visible.sync="centerDialogVisible">
      <div class="dialog_body">
        <div class="notic_content">
          <pre style="display:inline-block"></pre>
          {{Noticcontent}}
          <div class="sendtime">发布日期:{{Notictime}}</div>
        </div>
      </div>
      <el-button
        type="primary"
        size="small"
        @click="centerDialogVisible=false"
        style="display:block;margin:20px auto 0px auto"
      >确定</el-button>
    </el-dialog>

    <el-dialog class="Notic" :visible.sync="EditDialog" :title="edititle" width="60%">
      <span style="font-size:17px;color:#041f41">
        <b>录入通知公告信息:</b>
      </span>
      <div class="from">
        <el-form
          :model="NoticruleForm"
          :rules="noticrules"
          ref="NoticruleForm"
          label-width="140px"
          class="NoticruleForm"
        >
          <el-form-item label="通知公告标题" prop="title">
            <el-input placeholder="请输入发布标题" v-model="NoticruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="通知公告有效期" prop="timevalue">
            <el-date-picker
              v-model="timestart"
              type="date"
              :picker-options="startDatePicker"
              placeholder="选择通知公告生效日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <span>至</span>
            <el-date-picker
              v-model="timeend"
              type="date"
              :picker-options="endDatePicker"
              placeholder="选择通知公告失效日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="通知公告内容" prop="send_content">
            <el-input
              class="textarea"
              maxlength="500"
              type="textarea"
              v-model="NoticruleForm.send_content"
              placeholder="请输入公告内容"
            ></el-input>
            <span>{{L_content}}</span>
            <span style="color:red">/500(字数包括标点符号、空格和回车)</span>
          </el-form-item>
          <el-form-item label="相关文件" prop="file">
            <el-upload
              class="upload-demo"
              :data="uploadParams"
              :action="importurl"
              :auto-upload="false"
              :on-change="beforeupload"
              :on-success="filesuccess"
              :on-remove="fileremove"
              name="files"
              ref="upload"
              accept=".pdf"
            >
              <el-button size="mini" type="primary" class="import" style="width:auto">点击上传(仅支持PDF文件)</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="文件文号/通知编号" prop="document_num">
            <el-input placeholder="请输入文号" v-model.number="NoticruleForm.document_num"></el-input>
          </el-form-item>
          <el-form-item label="通知公告文件标题" prop="document_title">
            <el-input
              placeholder="请输入文件标题"
              v-model="NoticruleForm.document_title"
              :disabled="docum_title"
            ></el-input>
          </el-form-item>

          <el-form-item label="通知公告置顶" prop="radio">
            <el-radio-group v-model="NoticruleForm.radio">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发布人" prop="send_peopel">
            <el-input placeholder="请输入发布人" v-model="NoticruleForm.send_peopel"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="feicuilu" @click="submitForm('NoticruleForm')">发布</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var documentnum = (rule, value, callback) => {
     
      console.log("changdu", this.filelist, "value", value);
      if (this.filelist.name != undefined && (value === undefined || value == '')) {
        callback(new Error("请输入相关文号"));
      } else if (value !== undefined && value!=''&& this.filelist.name === undefined) {
        callback(new Error("输入文号后，必须上传文件"));
      } else if (this.filelist.name != undefined && value!='') {
        callback();
      } else if (this.filelist.name == undefined) {
        callback();
      }
    };
    var documentitle = (rule, value, callback) => {
      console.log(
        "changdu",
        this.filelist,
        "value",
        value,
        "value类型",
        typeof value
      );
      if (this.filelist.name != undefined && value === undefined) {
        callback(new Error("请输入文件标题"));
      } else if (
        value != undefined &&
        this.filelist.name == undefined &&
        value != ""
      ) {
        callback(new Error("输入文件标题后，必须上传文件"));
      } else {
        callback();
      }
    };
    var Timevalue = (rule,value,callback)=>{
      if(this.timestart && this.timeend){
        this.$set(this.NoticruleForm, "timevalue", [
        this.timestart,
        this.timeend
      ]);
        callback()
      }else {
        callback(new Error ("请输入通知公告的有效期和失效期"))
      }
    }
    return {
      ruleForm: {
        title: "",
        send_time: "",
        send_peopel: ""
      },
      timestart: "",
      timeend: "",
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      L_content: 0, // 内容字符大小限制
      rules: {},
      docum_title: false,
      filelist: {}, // 上传的文件列表
      importurl: "/index.php/inform/inform/save", // 增加的
      noticrules: {
        send_peopel: [
          { required: true, message: "请输入发布人姓名", trigger: "blur" }
        ],
        send_content: [
          { required: true, message: "请输入通知公告内容", trigger: "blur" },
          {
            min: 3,
            max: 500,
            message: "长度在 3 到 500个字符(包括标点符号、和空格)",
            trigger: "blur"
          }
        ],
        timevalue: [
          { validator: Timevalue, trigger: "change" }
        ],
        title: [
          { required: true, message: "请输入通知公告标题", trigger: "blur" }
        ],
        document_num: [{ validator: documentnum, trigger: "blur" }],
        document_title: [{ validator: documentitle, trigger: "blur" }]
      },
      uploadParams: {}, // 上传时的参数
      NoticruleForm: {
        radio: "1",
        timevalue: [],
        document_title: ""
      },
      height: 0,
      current_page: 1,
      sizepage: 15,
      edititle: "", // 新增还是修改
      EditDialog: false, // 新增还是修改 弹窗
      total: 0,
      selectdata: [],
      Notictitle: "",
      Noticunit_type: "",
      Noticpeople: "",
      Noticcontent: "",
      Notictime: "",
      centerDialogVisible: false,
      tableHeaderData: [
        {
          prop: "index",
          label: "序号",
          width: "60"
        },
        {
          prop: "send_peopel",
          label: "发布人",
          width: "80"
        },
        {
          prop: "import_time",
          label: "发布日期",
          width: "120"
        },
        {
          prop: "send_time",
          label: "公告有效期",
          width: "120"
        },
        {
          prop: "fail_time",
          label: "公告失效期",
          width: "120"
        },

        {
          prop: "radio",
          label: "置顶状态",
          width: "80"
        },
        {
          prop: "title",
          label: "公告标题"
        },
        {
          prop: "send_content",
          label: "公告内容"
        },
        {
          prop: "document_num",
          label: "相关文号",
          width: 80
        }
      ],
      Noticdata: []
    };
  },
  updated() {
    console.log("上传参数", this.NoticruleForm);
    //
    //console.log("起始日期",this.timestart,'结束日期',this.timeend)
    try {
      this.L_content = this.NoticruleForm.send_content.length; // 文字字数
    } catch (error) {}
    /*if (this.timestart && this.timeend) {
      this.$set(this.NoticruleForm, "timevalue", [
        this.timestart,
        this.timeend
      ]);
    }*/
    if (!this.EditDialog) {
      this.filelist = {};
    }
  },
  methods: {
    addNotci() {
      //新增通知公告
      this.NoticruleForm = {
        radio: "1"
      };
      this.timestart = "";
      this.timeend = "";
      this.edititle = "新增通知公告";
      this.EditDialog = true;
      this.L_content = 0;
      (this.importurl = "/index.php/inform/inform/save"), // 增加的
        /*this.$set(this.noticrules,'document_num',[])
            this.$set(this.noticrules,'document_title',[])*/
        (this.docum_title = false);
      try {
        this.$refs.upload.clearFiles();
      } catch (error) {}
    },

    upDataNotic(row) {
      this.docum_title = true; // 禁用文件标题
      this.timestart = row.timevalue[0]; // 生效起始值
      this.timeend = row.timevalue[1]; // 失效值
      if (row.dowloadfile != null) {
        this.filelist = { name: row.dowloadfile };
      } else {
        this.filelist = {}; // 清空上传文件的列表
      }
      try {
        this.$refs.upload.clearFiles();
      } catch (error) {}
      if ( parseInt(row.fail_time.replace(/-/g, "")) >=parseInt(this.getCurrentTime().replace(/-/g, ""))) {
        this.edititle = "修改通知公告";
        this.EditDialog = true;
        this.NoticruleForm = JSON.parse(JSON.stringify(row));
        this.NoticruleForm.document_num= this.NoticruleForm.document_num=='无'?'':this.NoticruleForm.document_num
        this.NoticruleForm.radio = row.radio == "是" ? "1" : "0";
        this.importurl = "/index.php/inform/inform/updateInform";
        if (this.NoticruleForm.dowloadfile) {
          let strindex = this.NoticruleForm.dowloadfile.indexOf("."); //22  截取字符
          this.$set(
            this.NoticruleForm,
            "document_title",
            this.NoticruleForm.dowloadfile.slice(13, strindex)
          );
        }
      } else {
        this.messages(0, "此消息已经过期，无法修改，请另行增加一条");
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log("验证通过");
          this.saveNotci();
        } else {
          this.messages(0, "请完善公告的所有必填项").catch(() => {});
        }
      });
    },

    dowloadfile(path) {
      if (path) {
        // window.location.href='/'+path
        window.open("/" + path);
      }
    },
    beforeupload(file) {
      console.log("上传", file.raw);
      this.docum_title = false;
      this.filelist = file;
      if (file.name) {
        /*  this.$set(this.noticrules,'document_num',[{required: true, message: '请输入文件文号', trigger: 'blur'},{type: 'number', message: '文号必须为数字值', trigger: 'blur'}])
                this.$set(this.noticrules,'document_title',[{required: true, message: '请输入文件标题', trigger: 'blur'}])*/
      }
      console.log(this.noticrules);
    },
    fileremove(file) {
      console.log("移除", file);
      this.filelist = {};
      /* this.$set(this.noticrules,'document_num',[])
              this.$set(this.noticrules,'document_title',[])*/
      console.log(this.noticrules);
    },
    saveNotci() {
      // 新增通知公告
      let fromdata = new FormData();
      const import_time = this.getCurrentTime();
      for (let key in this.NoticruleForm) {
        fromdata.append(key, this.NoticruleForm[key]);
      }
      fromdata.append("import_time", import_time);
      if (this.filelist.raw) {
        fromdata.append("files", this.filelist.raw);
      }
      let config = { headers: { "Content-Type": "multipart/form-data" } };
      this.$ajax.post(this.importurl, fromdata, config).then(res => {
        if (res.data.code == 1) {
          this.NoticruleForm = {};
          this.EditDialog = false;
          this.getNoticData();
        }
        this.messages(res.data.code, res.data.msg);
      });
    },
    filesuccess(file) {
      // 上传文件成功后的回调
      if (file.code == 1) {
        this.EditDialog = false;
        this.NoticruleForm = {};
        this.$refs.upload.clearFiles();
        this.getNoticData();
      }
      this.messages(file.code, file.msg);
    },
    detail(row) {
      this.centerDialogVisible = true;
      this.Notictitle = row.title;
      this.Noticunit_type = "交通厅";
      this.Noticpeople = row.send_peopel;
      this.Noticcontent = row.send_content;
      this.Notictime = row.send_time;
    },
    topNotic(row) {
      if (row.radio == "是") {
        this.messages(0, "此公告已经是置顶状态").catch(() => {
          return;
        });
      } else {
        this.$ajax
          .post("/index.php/inform/inform/isTop", { id: row.id })
          .then(res => {
            if (res.data.code == 1) {
              this.messages(1, "置顶成功!!").then(() => {
                return;
              });
              this.getNoticData();
            }else{
               this.messages(0, res.data.msg).catch(() => {
                return;
              });
            }
          });
      }
    },

    resetForm(formName) {
      // 重置查询的条件
      this.$refs[formName].resetFields();
    },
    getNoticData() {
      let parms = JSON.parse(JSON.stringify(this.ruleForm));
      parms.current_page = this.current_page;
      parms.per_page = this.sizepage;
      this.$ajax.post("/index.php/inform/inform/alllist", parms).then(res => {
        if (res.data.code == 1) {
          console.log("notic", res.data);
          res.data.msg.data.forEach((item, index) => {
            item.index = index + 1;
            item.fail_time = item.timevalue[1];
            item.send_time = item.timevalue[0];
            item.radio = item.radio == 1 ? "是" : "否";
            item.send_peopel = item.send_peope;
            item.document_num = item.document_num == null ? "无":item.document_num == ''?'无':item.document_num;
          });
          this.total = res.data.msg.total;
          this.Noticdata = res.data.msg.data;
        } else {
          this.messages(0, res.data.msg).catch(() => {});
          this.Noticdata = [];
        }
      });
    },
    handleSizeChange(sizepage) {
      console.log(sizepage);
      this.sizepage = sizepage;
      this.getNoticData();
    },
    handleCurrentChange(current_page) {
      console.log(current_page);
      this.current_page = current_page;
      this.getNoticData();
    },

    getCurrentTime() {
      let date = new Date();
      const current_date = date.getDate();
      // 获取本  日
      const current_month = date.getMonth() + 1;
      // 获取本  月
      const current_year = date.getFullYear();
      const import_time =
        current_year +
        "-" +
        (current_month >= 10 ? current_month : "0" + current_month) +
        "-" +
        current_date;
      return import_time;
    },
    beginDate() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.timeend) {
            return new Date(self.timeend).getTime() <= time.getTime();
            //return Date.now()<=self.timeend.getTime()
          } else {
            let yestoday = new Date();
            yestoday.setDate(yestoday.getDate() - 1);
            return yestoday.getTime() > time.getTime(); //开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    //提出结束时间必须大于提出开始时间
    processDate() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.timestart) {
            return new Date(self.timestart).getTime() >= time.getTime();
          } else {
            return time.getTime() <= Date.now(); //开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },

    confirm(text, fn) {
      this.$confirm(`${text}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          fn();
        })
        .catch(() => {
          return false;
        });
    },
    messages(code, text) {
      return new Promise((resolve, reject) => {
        if (code == 1) {
          this.$confirm(text, "提示", {
            confirmButtonText: "确定",
            type: "success"
          });
          resolve();
        } else {
          this.$confirm(text, "提示", {
            confirmButtonText: "确定",
            type: "error"
          }).then(() => {
            reject();
          });
        }
      });
    }
  },
  created() {
    this.height = window.screen.height - 225 + "px";
    this.getNoticData();
  }
};
</script>

<style lang="stylus" scoped>
.wrape-content {
  flex: 1;
  background: rgb(241, 242, 247);
  padding: 0% 1.1%;
}

.content {
  background: white;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
  padding-bottom: 40px;
}

.top {
  background: white;
  font-size: 13px;
  margin-bottom: 12px;
  color: #4D4D4D;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
  line-height: 35px;
  padding-left: 5px;

  span {
    margin-left: 5px;
  }
}

.form, .ruleForm >>> {
  .el-form-item__label-wrap {
    margin-left: 15px;
  }
}

.ruleForm {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  margin: 0 auto;

  .el-form-item {
    margin-bottom: 0px;
    margin-top: 9px;
    flex: 0 0 25%;
  }
}

.ruleForm >>> {
  .el-input__inner {
    height: 35px;
  }

  .el-cascader {
    line-height: 0px;
    display: block;
  }

  .el-select {
    width: 91%;
  }
}

.Table {
  margin-top: 9px;
  border-top: 1px solid #E5E5E5;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
}

.Table >>> {
  .el-table {
    th {
      background-color: rgba(235, 240, 255, 1) !important;
      padding: 8px 0;
    }
  }
}

.Table >>> {
  .el-table__body-wrapper {
    td {
      padding: 7.5px;
    }
  }
}

.el-pagination {
  padding: 1.1%;
  display: flex;
  justify-content: center;
  background: #F5F8FF;
}

.Table >>> {
  .el-table {
    .cell {
      padding: 0px;
    }
  }
}

.addbtn img, .exportbtn img, .deletebtn img {
  padding-right: 5px !important;
  vertical-align: bottom !important;
}

.ruleForm >>> {
  .el-form-item__content {
    line-height: 30px !important;
    margin-left: 72px !important;
  }
}

.el-table {
  margin-top: 11px !important;
}

.opreation {
  justify-self: start;
  margin-top: 10px;
  margin-left: 19px;
}

.noactive {
  background: #7CD1D1 !important;
}

.Table >>> {
  .grayrow {
    background: #FAFAFA !important;
  }
}

.ruleForm >>> {
  .el-form-item:nth-child(1) {
    .el-form-item__label-wrap {
      margin-left: 24px !important;
    }
  }
}

.Table >>> {
  .disabledrow {
    color: #24B3B3;
  }
}

.ruleForm>>> {
  .el-form-item {
    .el-input__inner:focus {
      border-color: #24B3B3;
      outline: 0;
    }
  }
}

.serchbtn {
  color: white;
  background: #24B3B3;
}

.serchbtn:hover {
  background: #1A9595;
  color: white;
}

.opleft {
  margin-right: 15px;
}

.ruleForm >>> {
  .el-form-item {
    .el-input {
      width: 87%;
    }
  }
}

.actionbtn {
  display: inline-block;
  width: 23px;
  height: 23px;
  padding: 2px 1px;
  margin-left: 5px;
  border-radius: 5px;
  cursor: pointer;
}

.dialog_body {
  height: 65%;
  border: 1px solid #bdbaba9c;
  box-shadow: 0px 0px 1px 0px #bdbaba63;
  border-radius: 5px;
}

.notic_content {
  width: 94%;
  margin: 0 auto;
  color: black;
  font-size: 16px;
  overflow: auto;
  line-height: 25px;
  letter-spacing: 2px;
}

.sendtime {
  float: right;
  margin-top: 30px;
  margin-bottom: 5px;
  font-size: 15px;
  color: grey;
}

.el-dialog__body {
  padding: 20px 20px !important;
}

.Notic >>>.el-dialog__header {
  background: rgb(4, 31, 65);
}

.Notic >>> ..el-dialog__footer {
  text-align: center;
}

.Notic >>> .el-dialog__title {
  color: white;
  font-size: 22px;
}

.textarea >>> {
  .el-textarea__inner {
    height: 150px;
  }
}

.NoticruleForm {
  display: flex;
  margin-top: 30px;
  flex-wrap: wrap;
  justify-content: flex-start;
  margin-left: 58px;

  .el-form-item {
    flex: 0 0 80%;
  }

  .el-select {
    display: block;
  }

  .el-cascader {
    display: block;
  }
}
</style>